package com.hsj.zuul.filter;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;

import javax.servlet.http.HttpServletRequest;

/**
 * @author:Teacher黄
 * @date:Created at 2020/01/02
 */
public class AccessFilter extends ZuulFilter {

    @Override
    public String filterType() {
        return "pre";
    }

    @Override
    public int filterOrder() {
        return 0;
    }

    @Override
    public boolean shouldFilter() {
        return true;
    }

    @Override
    public Object run() throws ZuulException {

        RequestContext currentContext = RequestContext.getCurrentContext();
        HttpServletRequest request = currentContext.getRequest();
        System.out.println(request.getRequestURL());
        // 获取token
        String token = request.getParameter("token");

        // 验证token
        if(token == null || token.isEmpty()){
            // 响应失败
            currentContext.setSendZuulResponse(false);
            currentContext.setResponseStatusCode(200);
            // 设置响应类型
            currentContext.getResponse().setContentType("application/json;charset=utf-8");
            // 响应体
            currentContext.setResponseBody("{\"code\": 403,\"msg\": \"token is wrong!\"}");

        }

        return null;
    }
}
